package cn.gson.springboot.model.service;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import cn.gson.springboot.model.dao.ChargeMoneyDAO;
import cn.gson.springboot.model.dao.DoctoradviceDetailDAO;
import cn.gson.springboot.model.dao.DoctorsAdviceDAO;
import cn.gson.springboot.model.dao.DrugDao;
import cn.gson.springboot.model.dao.HealthDAO;
import cn.gson.springboot.model.dao.HospitalProjectDAO;
import cn.gson.springboot.model.dao.LookHosprojectDAO;
import cn.gson.springboot.model.dao.LookHosprojectDetailsDAO;
import cn.gson.springboot.model.dao.LookillnessDAO;
import cn.gson.springboot.model.mapper.AdviceDetailsMappers;
import cn.gson.springboot.model.mapper.AdviceMappers;
import cn.gson.springboot.model.mapper.HealthMappers;
import cn.gson.springboot.model.mapper.LookillnessMapper;
import cn.gson.springboot.model.pojos.ChargeMoney;
import cn.gson.springboot.model.pojos.ChargemoneyDetail;
import cn.gson.springboot.model.pojos.DoctoradviceDetail;
import cn.gson.springboot.model.pojos.DoctorsAdvice;
import cn.gson.springboot.model.pojos.Drug;
import cn.gson.springboot.model.pojos.Health;
import cn.gson.springboot.model.pojos.HospitalProject;
import cn.gson.springboot.model.pojos.InhospitalReg;
import cn.gson.springboot.model.pojos.LookHosproject;
import cn.gson.springboot.model.pojos.LookHosprojectDetail;
import cn.gson.springboot.model.pojos.LookIllness;
import cn.gson.springboot.model.pojos.User;
import cn.gson.springboot.model.vo.AdviceVo;
import cn.gson.springboot.model.vo.ChargemoneyVo;
import cn.gson.springboot.model.vo.HospitalProjectVo;

@Service
@Transactional(rollbackOn=Exception.class)
public class LookillnessService {
            //看诊
	        @Autowired
             private LookillnessDAO ldao;
	        @Autowired 
	        private LookillnessMapper lm;
	         
	        //医嘱
	         @Autowired
	        private DoctorsAdviceDAO ddao;
	         
	         //医嘱详情
	         @Autowired
		     private  DoctoradviceDetailDAO  docdao;
	         
	         //体检记录
	         @Autowired
	     	private HealthMappers hmapper;
	        
	         //看诊与医疗项目
	         @Autowired
	         private LookHosprojectDAO hosdao;
	         
	         //看诊与医疗项目详情
	         @Autowired
	         private LookHosprojectDetailsDAO lookdetailsdao;
	         
	         @Autowired
	     	private DrugDao drugsdao;//药品的dao
	         
	        @Autowired
	        private HospitalProjectDAO hpdao;//医疗项目dao
	        
	        //收费主表
	        @Autowired
	        private ChargeMoneyDAO chdao;
	         
	       //医疗卡的service	
	    	@Autowired
	    	private ClinicCardService  ccs;
	    	
	    	//用户service
	    	@Autowired
	    	private UserService us;
	    	
	    	//挂号service
	    	@Autowired
	    	private RegistrFromService rs;
	    	
	    	//医嘱mapper
	    	@Autowired
	    	private AdviceMappers admapper;
	        
	    	//开体检项目
			//开立体检（新增体检表，医疗卡表，项目表）
			public void OutAddHealth(Integer look_id,String project_arr,String totalmoney) {
				    //分割体检项目编号
					String arr[] =project_arr.split(",");
					if(!"".equals(project_arr)) {
						for(int i=0;i<arr.length;i++) {
							hmapper.AddHealth(Integer.parseInt(arr[i]), look_id, null, 1, 1);
						}    
					}
			}
	     
	         //根据看诊id查询返回实体类
	         public LookIllness selectlookillness(Integer lid) {
	        	 if(ldao.existsById(lid)) {
	        		  return ldao.findById(lid).get();
	        	 }
	        	return null;
	         }
	         
	         //医疗项目主表新增
	         public void addhosproject(LookHosproject hp) {
	        	 hosdao.save(hp);
	         }
	         
	         //医疗项目主详情表新增
	         public void addhosprojectdetails(LookHosprojectDetail hdetailsp) {
	        	 lookdetailsdao.save(hdetailsp);
	         }
	         
	         //看诊查询到看诊id
	        public LookIllness selectBylookillness() {
	        	 return lm.selectBylookillness();
	         } 
	         
	         //看诊表新增
	      	public void savelookillness(AdviceVo advvo) {
	      		//获取vo看诊
	      		LookIllness lookentity = advvo.getLook();
	     		ldao.save(lookentity);
	      	}
	      	
	     	//二次看诊新增医嘱详情
	     	public void saveDocterredo(AdviceVo advvo){
                //获取vo类的医嘱详情
	     		List<DoctoradviceDetail> details = advvo.getDetails();
	     		
	     		//获取医嘱主表id
	     		DoctorsAdvice advice = advvo.getAdvice();
	     		System.out.println("advice:"+advice);
	     		advice.setDocadviceId(advvo.getAdvice().getDocadviceId());
	     		
	     		//药品添加
	     		for (DoctoradviceDetail pur : details) {
	     			//查询药品
	     			Drug drug = drugsdao.findById(pur.getDrug().getDrugNumber()).get();
	     			System.out.println("二药品的编号："+drug);
	     			System.out.println("用药频度："+pur.getDocdetailsDrugpingdu());
	     			System.out.println("用药用量："+pur.getDocdetailsDruguseliang());
	     			//重新赋值一下药品对象
	     			pur.setDrug(drug);
	     			
	     			//重新赋值一下医嘱主表id
	     			pur.setDoctorsAdvice(advice);
	     			
	     			//新增医嘱详情
	     			docdao.save(pur);
	     		}
	     	}
	         
	     	//开立医嘱（新增医嘱表，医嘱详情）
	     	public void saveDocter(AdviceVo advvo) {
	     		//获取医嘱进行新增
	     		DoctorsAdvice advice = advvo.getAdvice();
	     		
	     		//获取住院登记----空值
	     		InhospitalReg regentity = advvo.getReg();
	     		advice.setInhospitalReg(regentity);
	     		
	     		//获取vo看诊----查到看诊id做外键
	     		LookIllness lookentity = advvo.getLook();
	     		/*System.out.println("vo看诊id:"+lookentity.getLookillnessId());*/
	     		
	     		//查询看诊号
	     		LookIllness  lillness=  ldao.findById(lookentity.getLookillnessId()).get();
	     		/*System.out.println("vo看诊id2:"+lillness.getLookillnessId());    */                                                     
	     		
	     		//医嘱表里看诊的外键
	     		advice.setLookIllness(lillness);
	     		
	     		//时间
	     		advvo.getAdvice().setDocBegintime(new  Timestamp(new Date().getTime()));
	     		advvo.getAdvice().setDocEndtime(new Timestamp(new Date().getTime()));
	     		
	     		//医嘱新增
	     		ddao.save(advice);
	     		
	     		List<DoctoradviceDetail> details = advvo.getDetails();
	     		
	     		//循环
	     		for (DoctoradviceDetail pur : details) {
	     			//添加医嘱信息
	     			pur.setDoctorsAdvice(advice);
	     			//查询药品
	     			Drug drug = drugsdao.findById(pur.getDrug().getDrugNumber()).get();
	     			System.out.println("药品的编号："+drug);
	     			System.out.println("用药频度："+pur.getDocdetailsDrugpingdu());
	     			System.out.println("用药用量："+pur.getDocdetailsDruguseliang());
	     			//重新赋值一下药品对象
	     			pur.setDrug(drug);
	     			//新增医嘱详情
	     			docdao.save(pur);
	     		}
	     		
	     	}
	     	
	     	//开医疗项目
	     	public void saveHosproject(HospitalProjectVo hosvo) {
	     		//获取医疗项目记录表进行新增
	     		LookHosproject lhos=hosvo.getLookhosproject();
	     		
	     		//获取vo看诊----查到看诊id做外键
	     		LookIllness looks = hosvo.getLookillness();
	     		
	     		//查询看诊号
	     		LookIllness  lillness=  ldao.findById(looks.getLookillnessId()).get();
	     		
	     		//看诊与医疗项目----看诊的外键
	     		lhos.setLookIllness(lillness);
	     		
	     		//看诊与医疗项目新增
	     		hosdao.save(lhos);
	     		List<LookHosprojectDetail> hosprojectDetail = hosvo.getLookhosprojectdetails();
	     		
	     		for (LookHosprojectDetail p : hosprojectDetail) {
					//添加医疗项目信息
	     			p.setLookHosproject(lhos);
	     			//查询医疗项目
	     			HospitalProject hospitalProject = hpdao.findById(p.getHospitalProject().getHospitalProjectId()).get();
	     			/*System.out.println("医疗项目22222222-------的编号："+ hospitalProject.getHospitalProjectId());*/
	     			//医疗项目重新赋值
	     			p.setHospitalProject(hospitalProject);
	     			//看诊
	     			lookdetailsdao.save(p);
				}
	     	
	     	}
	     	
	     	//看诊文本框
			public  Map<String, Object> lookdoctorcliniccardid(@RequestParam("page")int page,
																											  @RequestParam("rows")int rows,
																											  HttpSession session, String cliniccardid,
																											  Integer registr_id){
			    /* 根据登录医生科室id
			     * 来显示看诊医生所看到
			     * 的自己科室所对应的病人
			     * ---最高管理员可以看诊所有未接诊的病人
			     * */
				Page<Object> pg = PageHelper.startPage(page, rows);
		       	//①获取登录人---权限控制
			     User user = (User)session.getAttribute("user");	
			     System.out.println("直接获取登录人id："+user.getUserId());
			     //②根据登录人的id查出登录人的角色
			     JSONArray selectLookpeople = ccs.selectLookDoctorBysid(null, user.getUserId());
			     System.out.println(selectLookpeople.size()+"---------根据登录人的id查出登录人的角色:"+selectLookpeople.getJSONObject(0).getString("role_name"));
                //③根据登录人的角色进行判断
			     String rolename = selectLookpeople.getJSONObject(0).getString("role_name");
			     System.out.println("登录人的角色："+rolename);
			     //④登录人为高级领导人：院长或是副院长--------》看诊查出所有未看诊但是分诊了的病人信息-----》接诊医生就是当前登录人
			     if(rolename.equals("院长") || rolename.equals("副院长")) {
			    	 //最高领导人不需要查出他的科室(cliniccardid,sectionid,registr_id为空)
			    	JSONArray returnlookpeople= ccs.lookdoctorclinic(1, null, null,null);
			    	System.out.println("领导人查询到病人信息："+returnlookpeople);
			    	   for (int i = 0; i < returnlookpeople.size(); i++) {
					    	 String logindname=returnlookpeople.getJSONObject(i).getString("registr_docname");
					    	 System.out.println("领导人for循环挂号医生：------"+logindname);
						     User uid = us.selectByname(logindname);
						     JSONObject o =  (JSONObject) returnlookpeople.get(i);
						     o.put("uid", uid.getUserId());
						}
			    	    Map<String,Object> map = new HashMap<>();
						map.put("total", pg.getTotal());//封装总记录数
						map.put("rows", returnlookpeople);//封装当前页的内容
			    	return  map;
			     }
			     
			     //如果是医生
			     if(rolename.equals("医生")) {
			    	 //根据医生角色与医生id查-----用来获取医生的科室id出现对应科室病人信息
			         JSONArray selectLookDoctorBysid = ccs.selectLookDoctorBysid("医生", user.getUserId());
				     Integer sectionid = null;
				     JSONArray returnlookdoctor = null;
				     //医生查询不为空
				     if(selectLookDoctorBysid.size()>0) {
				    	  System.out.println("是医生！！");
				    	  //医生科室id
				    	  sectionid=selectLookDoctorBysid.getJSONObject(0).getInteger("section_id");
					     //对应查询病人信息
					     returnlookdoctor = ccs.lookdoctorclinic(1, cliniccardid, sectionid,registr_id);
					     for (int i = 0; i < returnlookdoctor.size(); i++) {
					    	 String dnames=returnlookdoctor.getJSONObject(i).getString("registr_docname");
					    	 System.out.println("for循环挂号医生：------"+dnames);
						     User uid = us.selectByname(dnames);
						     JSONObject o =  (JSONObject) returnlookdoctor.get(i);
						     o.put("uid", uid.getUserId());
						}
					     System.out.println("加医生编号的语句：-----"+returnlookdoctor);
				     }
				     
				        Map<String,Object> map = new HashMap<>();
						map.put("total", pg.getTotal());//封装总记录数
						map.put("rows", returnlookdoctor);//封装当前页的内容
			    	return  map;
			     }
	
			      return null;
		}
			
			
			//叫号窗口初始化
			public Map<String, Object> lookdoctorcallNumber(@RequestParam("page")int page,
					   																	   @RequestParam("rows")int rows,
					   																	   	HttpSession session, 
					   																	   	String cliniccardid,
					   																	   	Integer registr_id){
			    /* 根据登录医生科室id
			     * 来显示看诊医生所看到
			     * 的自己科室所对应的病人
			     * ---最高管理员可以看诊所有未接诊的病人
			     * */
				Page<Object> pg = PageHelper.startPage(page, rows);
				
		       	//①获取登录人
			    User user = (User) session.getAttribute("user");	
			     System.out.println("直接获取登录人id："+user.getUserId());
			     //②根据登录人的id查出登录人的角色
			     JSONArray selectLookpeople = ccs.selectLookDoctorBysid(null, user.getUserId());
			     System.out.println(selectLookpeople.size()+"---------根据登录人的id查出登录人的角色:"+selectLookpeople.getJSONObject(0).getString("role_name"));
                //③根据登录人的角色进行判断
			     String rolename = selectLookpeople.getJSONObject(0).getString("role_name");
			     System.out.println("登录人的角色："+rolename);
			     //④登录人为高级领导人：院长或是副院长--------》看诊查出所有未看诊但是分诊了的病人信息-----》接诊医生就是当前登录人
			     if(rolename.equals("院长") || rolename.equals("副院长")) {
			    	 //最高领导人不需要查出他的科室(cliniccardid,sectionid,registr_id为空)
			    	JSONArray returnlookpeople= ccs.lookdoctorCall(0, 1, null, null, null);
			    	System.out.println("领导人查询到病人信息："+returnlookpeople);
			    	   for (int i = 0; i < returnlookpeople.size(); i++) {
					    	 String logindname=returnlookpeople.getJSONObject(i).getString("registr_docname");
					    	 System.out.println("领导人for循环挂号医生：------"+logindname);
						     User uid = us.selectByname(logindname);
						     JSONObject o =  (JSONObject) returnlookpeople.get(i);
						     o.put("uid", uid.getUserId());
						}
			    	    Map<String,Object> map = new HashMap<>();
						map.put("total", pg.getTotal());//封装总记录数
						map.put("rows", returnlookpeople);//封装当前页的内容
			    	return map;
			     }
			     
			     //如果是医生
			     if(rolename.equals("医生")) {
			    	 //根据医生角色与医生id查-----用来获取医生的科室id出现对应科室病人信息
			         JSONArray selectLookDoctorBysid = ccs.selectLookDoctorBysid("医生", user.getUserId());
				     Integer sectionid = null;
				     JSONArray returnlookdoctor = null;
				     //医生查询不为空
				     if(selectLookDoctorBysid.size()>0) {
				    	  System.out.println("是医生！！");
				    	  //医生科室id
				    	  sectionid=selectLookDoctorBysid.getJSONObject(0).getInteger("section_id");
					     //对应查询病人信息
					     returnlookdoctor = ccs.lookdoctorCall(0,1,cliniccardid, sectionid,registr_id);
					     for (int i = 0; i < returnlookdoctor.size(); i++) {
					    	 String dnames=returnlookdoctor.getJSONObject(i).getString("registr_docname");
					    	 System.out.println("for循环挂号医生：------"+dnames);
						     User uid = us.selectByname(dnames);
						     JSONObject o =  (JSONObject) returnlookdoctor.get(i);
						     o.put("uid", uid.getUserId());
						}
					     System.out.println("加医生编号的语句：-----"+returnlookdoctor);
				     }
				     Map<String,Object> map = new HashMap<>();
						map.put("total", pg.getTotal());//封装总记录数
						map.put("rows", returnlookdoctor);//封装当前页的内容
				     return map;
			     }
	
			      return null;
		}	
			
		//看诊修改
		public void UpdateLookillnessq(Integer docadvice_id,Integer lookillnessId,String lookinessReason,String lookinessResult,String docadviceConent) {
			 //看诊
			System.out.println("lookillnessId--------------"+lookillnessId);
			 lm.updateLookillness(lookinessResult, lookinessReason, lookillnessId);
			 //修改医嘱内容
			 System.out.println("service医嘱id---------------------:"+docadvice_id);
			 admapper.updateAdvice(docadviceConent,docadvice_id);
		}
		
		//修改看诊
		public void updateLookillness(Integer lookid,String lookinessReason,String lookinessResult) {
		 lm.updateLookillness(lookinessResult, lookinessReason, lookid);
		}
		
		//修改医嘱
		public void updateAdvice(Integer docadvice_id,String docadviceConent) {
		 admapper.updateAdvice(docadviceConent,docadvice_id);
		}
		
		/*LookIllness illness=ldao.findById(lookillnessId).get();
		System.out.println("lookinessReason--------------"+lookinessReason);
		System.out.println("lookinessResult--------------"+lookinessResult);
		System.out.println("docadviceConent--------------"+docadviceConent);

		//病因
		illness.setLookinessReason(lookinessReason);
		//结果
		illness.setLookinessResult(lookinessResult);
		//修改了看诊
		ldao.save(illness);*/
	         
}

